package com.sunway.netty.thirdexample;

import java.util.Iterator;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChatServerHandler extends SimpleChannelInboundHandler<String>{

	//保存客户端连接的Channel信息
	private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		Channel channel = ctx.channel();
		
		//遍历已经保存的客户端，然后向其发送数据
		Iterator<Channel> iterator = channelGroup.iterator();
		while(iterator.hasNext()) {
			Channel ch = iterator.next();
			if(ch != channel) {
				ch.writeAndFlush(ch.remoteAddress() + " 发送的消息: " + msg + "\n");
			}
			else {
				ch.writeAndFlush("[自己]: " + msg + "\n");
			}
		}
		
//		//JAVA 8 lamda表达式方式遍历
//		channelGroup.forEach(ch -> {
//			if(ch != channel) {
//				ch.writeAndFlush(ch.remoteAddress() + " 发送的消息: " + msg + "\n");
//			}
//			else {
//				ch.writeAndFlush("[自己]: " + msg + "\n");
//			}
//		});
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.channel().close();
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		//客户端建立连接时的回调函数
		Channel channel = ctx.channel();
		channelGroup.writeAndFlush("[服务器] - " + channel.remoteAddress() + " 加入\n");
		channelGroup.add(channel);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		//客户端断开连接的回调函数
		Channel channel = ctx.channel();
		
		channelGroup.writeAndFlush("[服务器] - " + channel.remoteAddress() + " 退出\n");
		//不需要手动移除，当连接断开时ChannelGroup会自动移除
		//channelGroup.remove(channel);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//客户端连接成功建立时的回调函数
		Channel channel = ctx.channel();
		System.out.println(channel.remoteAddress() + " 上线");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		System.out.println(channel.remoteAddress() + " 下线");
	}

	
	
}
